package com.doushu.websocket.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
//import com.doushu.websocket.common.property.DispatchProperty;
import com.doushu.websocket.dto.ChromeDto;
import com.doushu.websocket.dto.ErrorDto;
//import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.EOFException;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/")
@Component
public class WebSocketServer {

    // concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    public static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<String, WebSocketServer>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private String shopToken;

//    private DispatchProperty dispatchProperty;

    // 启动类set注入，调用下面set方法
//    private static ApplicationContext applicationContext;

//    public static void setApplicationContext(ApplicationContext context) {
//        applicationContext = context;
//    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
//        dispatchProperty = applicationContext.getBean(DispatchProperty.class);
    }

    @OnClose
    public void onClose() {
        if (this.shopToken != null && webSocketMap.get(this.shopToken) != null) {
            webSocketMap.remove(this.shopToken);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        if(!message.equals("YsPing")) {
            try {
                ChromeDto chromeDto = JSON.parseObject(message, new TypeReference<ChromeDto>() {
                });
                if (chromeDto.getRunAsShopId() != null) {
                    if (chromeDto.getToken() == null) {
                        chromeDto.setToken("");
                    }
                    if (this.shopToken != null) {
                        webSocketMap.remove(this.shopToken);
                    }
                    this.shopToken = chromeDto.getRunAsShopId() + "_" + chromeDto.getToken();
                    webSocketMap.putIfAbsent(this.shopToken, this);
                    System.out.println("来自客户端的消息:" + message);
                }
            } catch (Exception e) {
                ErrorDto errorDto = new ErrorDto();
                errorDto.setType("error");
                this.sendMessage(JSON.toJSONString(errorDto));
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        if (error instanceof EOFException) {
            return;
        }
    }

    public void sendMessage(String message) throws IOException {
        synchronized (this.session) {
            this.session.getBasicRemote().sendText(message);
        }
    }


}
